package com.xinqiupark.technology.ui.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.xinqiupark.technology.R;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.SAXParserFactory;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class XmlParseActivity extends AppCompatActivity {

    @BindView(R.id.tv_content)
    TextView mTvContent;

    private String mResult;

    /*
      请求网络数据
       */
    @OnClick(R.id.btn_request_data)
    public void sendRequestWithOkHttp(View view) {

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.52.1/get_data.xml")
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(getClass().getSimpleName(), "请求失败");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        mResult = response.body().string();

                        runOnUiThread(() -> Toast.makeText(XmlParseActivity.this,
                                "请求网络成功", Toast.LENGTH_SHORT).show());
                    }
                }
            }
        });
    }

    /*
   Xml pull解析方式
    */
    @SuppressLint("SetTextI18n")
    @OnClick(R.id.btn_xml_pull)
    public void onXmlPull(View view) {
        if (!TextUtils.isEmpty(mResult)) {
            try {
                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                XmlPullParser pullParser = factory.newPullParser();

                pullParser.setInput(new StringReader(mResult));

                int eventType = pullParser.getEventType();

                String id = "";
                String name = "";
                String version = "";

                while (eventType != XmlPullParser.END_DOCUMENT) {
                    String nodeName = pullParser.getName();

                    switch (eventType) {
                        case XmlPullParser.START_TAG: {
                            if ("id".equals(nodeName)) {
                                id = pullParser.nextText();
                            } else if ("name".equals(nodeName)) {
                                name = pullParser.nextText();
                            } else if ("version".equals(nodeName)) {
                                version = pullParser.nextText();
                            }
                            break;
                        }
                        case XmlPullParser.END_TAG: {
                            if ("app".equals(nodeName)) {
                                mTvContent.setText("id is" + id);
                                Log.d(getClass().getSimpleName(), "id is" + id);
                                Log.d(getClass().getSimpleName(), "name is" + name);
                                Log.d(getClass().getSimpleName(), "version is" + version);
                            }
                            break;
                        }
                        default:
                            break;
                    }
                    eventType = pullParser.next();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /*
    Xml Sax解析
     */
    @OnClick(R.id.btn_xml_sax)
    public void onXmlSax(View view) {
        if (!TextUtils.isEmpty(mResult)) {
            try {
                SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
                XMLReader xmlReader = saxParserFactory.newSAXParser().getXMLReader();
                ContentHandler handler = new ContentHandler();
                xmlReader.setContentHandler(handler);
                //开始执行解析
                xmlReader.parse(new InputSource(new StringReader(mResult)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xml_parse);
        ButterKnife.bind(this);
    }


    public class ContentHandler extends DefaultHandler {
        private String nodeName;

        private StringBuilder id;

        private StringBuilder name;

        private StringBuilder version;

        @Override
        public void startDocument() throws SAXException {
            id = new StringBuilder();
            name = new StringBuilder();
            version = new StringBuilder();
        }

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            //记录当前节点
            nodeName = localName;
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            if ("id".equals(nodeName)) {
                id.append(ch, start, length);
            } else if ("name".equals(nodeName)) {
                name.append(ch, start, length);
            } else if ("version".equals(nodeName)) {
                version.append(ch, start, length);
            }
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            if ("app".equals(localName)) {
                Log.d(getClass().getSimpleName(), "id is" + id.toString().trim());
                Log.d(getClass().getSimpleName(), "name is" + name.toString().trim());
                Log.d(getClass().getSimpleName(), "version is" + version.toString().trim());
                //清空存储
                id.setLength(0);
                name.setLength(0);
                version.setLength(0);

                mTvContent.setText("id is" + id.toString().trim());
            }
        }

        @Override
        public void endDocument() throws SAXException {
            super.endDocument();
        }
    }
}
